<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2 class="register-title">用户注册</h2>
      <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" label-position="top">
        <el-form-item label="用户名" prop="username">
          <el-input
            style="width: 100%"
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            style="width: 100%"
            v-model="registerForm.nickname"
            placeholder="请输入昵称"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            style="width: 100%"
            v-model="registerForm.password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            type="password"
            show-password
            clearable
            @input="onPasswordInput"
          />
          <div class="password-strength-wrapper">
            <div class="password-strength-text">密码强度：{{ passwordStrengthText }}</div>
            <div class="password-strength-bar">
              <div
                class="password-strength-indicator"
                :style="{ width: `${passwordStrength * 25}%` }"
                :class="passwordStrengthClass"
              ></div>
            </div>
            <div class="password-tips">密码必须包含：大写字母、小写字母、数字和特殊字符，长度至少8位</div>
          </div>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            style="width: 100%"
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码"
            prefix-icon="Lock"
            type="password"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" class="register-button" @click="handleRegister">
            注册
          </el-button>
          <div class="form-actions">
            <el-link type="primary" @click="goToLogin">已有账号？返回登录</el-link>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { register } from "@/api/auth";
import {
  validatePasswordComplexity,
  checkPasswordStrength,
  getPasswordStrengthText,
  getPasswordStrengthClass,
} from "@/utils/validators";

const router = useRouter();
const registerFormRef = ref(null);
const loading = ref(false);
const passwordStrength = ref(0);

// 注册表单数据
const registerForm = reactive({
  username: "",
  nickname: "",
  password: "",
  confirmPassword: "",
});

// 密码强度文本
const passwordStrengthText = computed(() => {
  return getPasswordStrengthText(passwordStrength.value);
});

// 密码强度样式类
const passwordStrengthClass = computed(() => {
  return getPasswordStrengthClass(passwordStrength.value);
});

// 检查密码强度
const onPasswordInput = (value) => {
  const password = value || registerForm.password;
  passwordStrength.value = checkPasswordStrength(password);
};

// 校验密码是否一致
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== registerForm.password) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度应在3-20个字符之间", trigger: "blur" },
  ],
  nickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 20, message: "昵称长度应在2-20个字符之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { validator: validatePasswordComplexity, trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
};

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  await registerFormRef.value.validate(async (valid) => {
    if (!valid) return;

    loading.value = true;
    try {
      const { confirmPassword, ...registerData } = registerForm;
      const res = await register(registerData);

      if (res.success) {
        ElMessage.success("注册成功，请登录");
        router.push("/login");
      }
    } catch (error) {
      console.error("注册出错：", error);
      ElMessage.error(error.message);
    } finally {
      loading.value = false;
    }
  });
};

// 跳转到登录页
const goToLogin = () => {
  router.push("/login");
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.register-card {
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.register-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.password-strength-wrapper {
  margin-top: 5px;
}

.password-strength-text {
  font-size: 12px;
  margin-bottom: 4px;
  color: #606266;
}

.password-strength-bar {
  height: 6px;
  background-color: #ebeef5;
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 4px;
}

.password-strength-indicator {
  height: 100%;
  transition: all 0.3s;
}

.strength-weak {
  background-color: #f56c6c;
}

.strength-medium {
  background-color: #e6a23c;
}

.strength-strong {
  background-color: #409eff;
}

.strength-very-strong {
  background-color: #67c23a;
}

.password-tips {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
}
</style>
